package com.dongdongshop.controller;


import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.dongdongshop.api.UserServiceApi;
import com.dongdongshop.data.Result;
import com.dongdongshop.dto.UserDTO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;


import java.util.HashMap;
import java.util.Map;


@Controller
@RequestMapping("weibo")
@CrossOrigin
public class WeiboLoginController {
    @Autowired
    private UserServiceApi userServiceApi;
    @Autowired
    private LoginController loginController;

    @Value("${weibo.accessToken}")
    private String accessToken;

    @Value("${weibo.appID}")
    private String appID;

    @Value("${weibo.appKEY}")
    private String appKEY;

    @Value("${weibo.redirectURI}")
    private String redirectURI;

    @Value("${weibo.authorizeURL}")
    private String authorizeURL;

    @Value("${weibo.userJson}")
    private String userJson;

    @Value("${weibo.grantType}")
    private String grantType;

    //回调函数
    @RequestMapping("back")
    public String WeiboLogin() {
        return "back";
    }

    //微博登陆
    @RequestMapping("login")
    public String login(@RequestParam String code, Model model) {
        Map<String, Object> map = new HashMap<>();
        map.put("client_id", appID);
        map.put("client_secret", appKEY);
        map.put("grant_type", grantType);
        map.put("redirect_uri", redirectURI);
        map.put("code", code);
        /*调用接口,授权获取到uid与access_token*/
        String s = HttpUtil.post(accessToken, map);
        Map<String, String> parse = (Map<String, String>) JSON.parse(s);
        String access_token = parse.get("access_token");
        String uid = parse.get("uid");
        /*调用接口,获取到微博用户的各种信息*/
        String s2 = HttpUtil.get(userJson + "?access_token=" + access_token + "&uid=" + uid);
        Map<String, String> parse2 = (Map<String, String>) JSON.parse(s2);
        //先判断数据库中是否有该用户,有直接登陆,没有则去注册并登陆
        Result<UserDTO> userResult = userServiceApi.getUserByName(parse2.get("screen_name"));
        if (userResult.getData() == null) {
            //成功获取到微博用户的uid与uname,去注册
            UserDTO userDTO = new UserDTO();
            userDTO.setUsername(parse2.get("screen_name"));
            userDTO.setPassword("1234");
            userServiceApi.registerWeibo(userDTO);
        }
        Result<UserDTO> result = userServiceApi.getUserByName(parse2.get("screen_name"));
        UserDTO userDTO = result.getData();
        //直接去登陆
        Result result2 = loginController.login(userDTO.getUsername(), "1234");
        model.addAttribute("token", result2.getData());//token
        return "loginSuccess";
    }

}
